import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    isLoggedIn: false,
    role: '',
    loginTime: null, // 添加登录时间状态
    id: null,
    username: ''
  }),
  actions: {
    login(userData) {
      this.isLoggedIn = true;
      this.loginTime = new Date().toISOString(); // 记录登录时间
      this.role = userData.role;
      this.id = userData.id;
      this.username = userData.username;
      localStorage.setItem('currentUser', JSON.stringify(userData));
    },
    logout() {
      this.isLoggedIn = false;
      this.role = '';
      this.loginTime = null; // 登出时清除登录时间
      this.id = null;
      this.username = '';
      localStorage.removeItem('currentUser');
    },
    initialize() {
      const user = localStorage.getItem('currentUser');
      if (user) {
        const userData = JSON.parse(user);
        this.isLoggedIn = true;
        this.role = userData.role;
        this.loginTime = userData.loginTime; // 初始化时恢复登录时间
        this.id = userData.id;
        this.username = userData.username;
      }
    }
  }
})